<template>
  <el-drawer
      v-model="localVisible"
      :show-close="false"
      size="80%"
      :destroy-on-close="true"
  >
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">任务详情信息</h4>
    </template>
    <div>
      <zh-row>
        <zh-col :span="state.wtTaskVO.createOrAssignPerson === 2? 18:24">
          <div style="height: calc(100vh - 100px);overflow-y: auto;">
            <zh-col :span="24">
              <zh-card title="任务信息">
                <zh-form :model="state.wtTaskVO" ref="queryFormRef" label-width="150px">
                  <zh-form-input prop="taskName" label="任务名称"
                                 v-model="state.wtTaskVO.taskName" disabled></zh-form-input>
                  <zh-form-input prop="taskDesc" label="任务描述"
                                 v-model="state.wtTaskVO.taskDesc" disabled></zh-form-input>
                  <zh-form-select
                      prop="taskType"
                      label="任务类型"
                      placeholder="单选"
                      allowClear
                      :options="state.dictData.WTTASKTYPE"
                      v-model="state.wtTaskVO.taskType"
                      disabled
                  ></zh-form-select>
                  <zh-form-date prop="taskStartTime" label="任务开始日期" format="YYYY-MM-DD"
                                v-model="state.wtTaskVO.taskStartTime" disabled></zh-form-date>
                  <zh-form-date prop="taskEndTime" label="任务结束日期" format="YYYY-MM-DD"
                                v-model="state.wtTaskVO.taskEndTime" disabled></zh-form-date>
                  <zh-form-input prop="taskStatusName" label="总体任务状态"
                                 v-if="state.wtTaskVO.createOrAssignPerson === 1"
                                 v-model="state.wtTaskVO.taskStatusName" disabled></zh-form-input>
                  <zh-form-input prop="taskStatusName" label="当前任务状态"
                                 v-if="state.wtTaskVO.createOrAssignPerson === 2"
                                 v-model="state.wtTaskVO.taskAllocaStatusName" disabled></zh-form-input>
                  <zh-form-select
                      prop="taskPriority"
                      label="任务优先级"
                      placeholder="单选"
                      allowClear
                      :options="state.dictData.TAKSPRIORITY"
                      v-model="state.wtTaskVO.taskPriority"
                      disabled
                  ></zh-form-select>
                  <zh-form-input prop="createFullName" label="创建人"
                                 v-model="state.wtTaskVO.createFullName" disabled></zh-form-input>
                  <zh-form-input prop="orgName" label="创建人所属组织"
                                 v-model="state.wtTaskVO.orgName" disabled></zh-form-input>
                  <zh-form-select
                      v-if="state.wtTaskVO.createOrAssignPerson === 1"
                      prop="isAssign"
                      label="是否分配人员"
                      placeholder="单选"
                      allowClear
                      :options="[{dictKey: 0,dictValue: '未分配'},{dictKey: 1,dictValue: '已分配'}]"
                      v-model="state.wtTaskVO.isAssign"
                      disabled
                  ></zh-form-select>
                  <zh-form-input prop="taskLabel" label="任务标签"
                                 v-model="state.wtTaskVO.taskLabel" disabled></zh-form-input>
                  <zh-form-input prop="predictWorkHours" label="预估工时"
                                 v-model="state.wtTaskVO.predictWorkHours" disabled></zh-form-input>
                  <zh-form-date label="任务完成时间" prop="completedTime" type="datetime" disabled
                                v-model="state.wtTaskVO.completedTime" format="YYYY-MM-DD HH:mm:ss"></zh-form-date>
                  <zh-form-input prop="remarks" label="任务备注" disabled
                                 v-model="state.wtTaskVO.remarks"></zh-form-input>
                  <zh-form-input prop="taskRealProgress" label="任务进度" disabled
                                 v-model="state.wtTaskVO.taskRealProgressLabel"></zh-form-input>
                </zh-form>
              </zh-card>
            </zh-col>
            <zh-col :span="24" v-if="state.wtTaskVO.completeOperaFlag">
              <zh-card>
                <formForExecuteWtTask :taskRealProgressLabel="state.wtTaskVO.taskRealProgressLabel" ref="formForExecuteWtTaskPage"
                                      @update:taskRealProgressLabel="updateTaskRealProgressLabel"></formForExecuteWtTask>
              </zh-card>
            </zh-col>
            <zh-col :span="24">
              <zh-card title="子级任务" :body-style="{ padding: '0px', borderStyle: 'none' }">
                <vxe-grid v-bind="gridOptions">
                  <template #taskAllocaStatus="{ row }">
                    <el-tag v-if="row.taskAllocaStatus !== null"
                            v-for="e in taskAllocaStatusFilter(row.taskAllocaStatus)"
                            :key="e.label"
                            :type="e.type"
                            effect="dark"
                    >
                      {{ e.label }}
                    </el-tag>
                    <span v-else>
                  <el-tag type="danger">
                    未分配
                  </el-tag>
                </span>
                  </template>
                </vxe-grid>
              </zh-card>
            </zh-col>
            <zh-col :span="24">
              <logTableForWtTask ref="myWtTaskLog" :logOperateFlag="state.wtTaskVO.completeOperaFlag" v-model="state.commitLogList"
                                 :taskId="state.wtTaskVO.taskId" :wtTaskAllocationId="state.wtTaskVO.wtTaskAllocationId"
                                 v-if="state.wtTaskVO.createOrAssignPerson === 2" @refresh="getLogList"></logTableForWtTask>
            </zh-col>
          </div>
        </zh-col>
        <zh-col :span="6" v-if="state.wtTaskVO.createOrAssignPerson === 2">
          <div style="height: calc(100vh - 100px);overflow-y: auto;">
            <el-timeline>
              <el-timeline-item  placement="top"
                                v-for="(executeLog, index) in state.executeLogList" :timestamp="executeLog.createTime"
                                :key="index">
                <el-card>
                  <h4>{{ executeLogTitle(executeLog.operation) }}</h4>
                  <div v-if="executeLog.taskDescribe">
                    任务说明:{{executeLog.taskDescribe}}
                  </div>
                  <div v-if="executeLog.taskRemarks">
                    任务备注:{{executeLog.taskRemarks}}
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </zh-col>
      </zh-row>
    </div>

    <template #footer>
      <zh-button v-func:wtTask004 buttonType="edit" type="primary" @click="startWtTask" v-if="state.wtTaskVO.startOperaFlag">开启 </zh-button>
      <zh-button v-func:wtTask004 buttonType="edit" type="primary" @click="executeWtTask" v-if="state.wtTaskVO.completeOperaFlag">
        {{ state.completeWtTaskTitle }} </zh-button>
      <zh-button v-func:wtTask003 buttonType="add" @click="createChildWtTask" v-if="state.wtTaskVO.createChildTaskOperaFlag">创建子任务 </zh-button>
    </template>
  </el-drawer>

  <zh-dialog
      title="任务开启"
      width="30%"
      v-model="state.startWtTaskVisible"
  >
    <template v-slot:footer>
      <el-button @click="cancelStartWtTask"> 关闭 </el-button>
      <el-button type="primary" @click="handleStartWtTask"> 开启 </el-button>
    </template>
    <formForStartWtTask ref="startWtTaskForm"></formForStartWtTask>
  </zh-dialog>

  <zh-dialog
      title="创建子任务"
      width="30%"
      v-model="state.createWtTaskVisible"
      @confirm="handleCreateOrEditWtTask"
      @cancel="cancelCreateOrEditWtTask"
  >
    <formForCreateWtTask v-model="state.childWtTaskVO"></formForCreateWtTask>
  </zh-dialog>
</template>

<script lang="ts" setup name="wtTaskDetailDrawer">
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import logTableForWtTask from './logTableForWtTask.vue'
import formForExecuteWtTask from './formForExecuteWtTask.vue'
import formForStartWtTask from './formForStartWtTask.vue'
import formForCreateWtTask from './formForCreateWtTask.vue'
const emits = defineEmits(["update:modelValue"]);

const props = defineProps({
  visible: {
    type: Boolean,
    required: false,
    default: () => {
      return false;
    },
  },
  taskId: {
    type: String,
    required: false
  },
  wtTaskAllocationId: {
    type: String,
    required: false
  },
  createOrAssignPerson: {
    type: Number,
    required: true
  },
});
let localVisible = ref();
const myWtTaskLog = ref(null);
const startWtTaskForm = ref(null);
const formForExecuteWtTaskPage = ref(null);

const state = reactive({
  wtTaskVO: {
    taskName: undefined,
    taskDesc: undefined,
    taskType: undefined,
    taskStartTime: undefined,
    taskEndTime: undefined,
    taskStatus: undefined,
    taskPriority: undefined,
    createFullName: undefined,
    orgName: undefined,
    isAssign: undefined,
    taskLabel: undefined,
    predictWorkHours: undefined,
    completedTime: undefined,
    remarks: undefined,
    taskRealProgress: undefined
  },
  childWtTaskVO: {
    taskName: undefined,
    taskDesc: undefined,
    taskType: undefined,
    taskStartTime: undefined,
    taskEndTime: undefined,
    taskStatus: undefined,
    taskPriority: undefined,
    createFullName: undefined,
    orgName: undefined,
    isAssign: undefined,
    taskLabel: undefined,
    predictWorkHours: undefined,
    completedTime: undefined,
    remarks: undefined,
    taskRealProgress: undefined,
    createWtTaskForChild: true
  },
  dictData: {},
  startWtTaskVisible: false,
  selectParentTaskId: undefined,
  createWtTaskVisible: false,
  completeWtTaskTitle: '',
  commitLogList: [],
  executeLogList: []
})

const gridOptions = reactive({
  showOverflow: true,
  border: 'outer',
  treeConfig: {
    transform: true,
    rowField: 'rowId',
    parentField: 'rowParentId',
    showLine: true
  },
  columns: [
    { field: "taskName", title: "任务名称", align: "center", width: 180,treeNode: true },
    { field: "taskDesc",title: "任务描述",align: "center",width: 200,},
    { field: "taskStartTime",title: "任务开始日期",align: "center",width: 120,},
    { field: "taskEndTime",title: "任务结束日期",align: "center",width: 120,},
    { field: "taskStatusName", title: "任务状态", align: "center", width: 80,editRender: {},
      slots: {
        // 使用插槽模板渲染
        default: "taskAllocaStatus",
      } },
    { field: "fullName", title: "分配人员", align: "center", width: 200 },
    { field: "taskRealProgressLabel", title: "任务最终进度", align: "center", width: 120},
    { field: "taskLabel", title: "任务标签", align: "center" , width: 80},
    { field: "predictWorkHours", title: "预估工时", align: "center", width: 80},
    { field: "taskWorkRatioLabel", title: "工作量占比", align: "center", width: 120 },
    { field: "createFullName", title: "创建人", align: "center", width: 100 },
    { field: "orgName", title: "创建人所属组织", align: "center", width: 150 },
    { field: "createTime", title: "创建时间", align: "center", width: 200 },
    { field: "remarks", title: "备注", align: "center", width: 120 },
  ],
  data: []
})

const taskAllocaStatusList = ref<Array<Item>>([
  {type: "info", label: "未开始", value: 0},
  {type: "primary", label: "进行中", value: 1},
  {type: "success", label: "已完成", value: 2},
]);


watch(
    () => props.visible,
    () => {
      localVisible.value = props.visible;
    }
);
watch(
    () => localVisible.value,
    () => {
      emits("update:modelValue", localVisible.value);
      if(localVisible.value){
        $api.common.send
            .post('wtTaskQuery002', {taskId: props.taskId,wtTaskAllocationId: props.wtTaskAllocationId,createOrAssignPerson: props.createOrAssignPerson})
            .then((res) => {
              state.wtTaskVO = res.result;
              state.wtTaskVO.taskType = state.wtTaskVO.taskType + "";
              getChildList();
              getLogList();
            })
            .catch(() => {});
      }else {
        resetData();
      }
    }
);

function executeLogTitle(val) {
  switch (val){
    case 1:
      return '任务开始';
    case 2:
      return '修改进度';
    case 3:
      return '提交日志';
    case 4:
      return '任务完成';
  }
}

function cancelDrawer() {
  localVisible.value = false;
}

function updateTaskRealProgressLabel(val) {
  if(val === '100%'){
    state.completeWtTaskTitle = '完成';
  }else {
    state.completeWtTaskTitle = '修改进度';
  }
}

function initDict() {
  const params = {
    dictFields: "WTTASKTYPE",
  };
  $api.common.getBatchDict.post(params).then((res) => {
    state.dictData = res.result;
  });
}

//获取子级任务
function getChildList() {
  $api.common.send
      .post('wtTaskQuery003', {taskId: state.wtTaskVO.taskId,createOrAssignPerson: state.wtTaskVO.createOrAssignPerson})
      .then((res) => {
        gridOptions.data = res.result;
      })
      .catch(() => {});
}

const taskAllocaStatusFilter = (taskAllocaStatus) => {
  return taskAllocaStatusList.value.filter((item) => item.value == taskAllocaStatus);
};


//开启任务-弹出框
function startWtTask() {
  state.startWtTaskVisible = true;
}

function cancelStartWtTask() {
  state.startWtTaskVisible = false;
}

//处理开启任务
function handleStartWtTask() {
  const params = {taskId: state.wtTaskVO.taskId};
  Object.assign(params,startWtTaskForm.value?.getData());
  $api.common.send
      .post("wtTask004", params)
      .then(() => {
        $messageBox.success("任务开启成功", "提示");
        cancelStartWtTask();
        getChildList();
      })
      .catch(() => {});
}

function executeWtTask() {
  const params = {taskId: state.wtTaskVO.taskId};
  Object.assign(params,formForExecuteWtTaskPage.value.getData())
  $api.common.send
      .post("wtTask005", params)
      .then(() => {
        if(state.completeWtTaskTitle === '完成'){
          $messageBox.success("任务完成成功", "提示");
        }else {
          $messageBox.success("任务修改进度成功", "提示");
        }
        cancelDrawer();
      })
      .catch(() => {});
}


//创建子级任务
function createChildWtTask() {
  state.selectParentTaskId = state.wtTaskVO.taskId;
  state.createWtTaskVisible = true;
}

function cancelCreateOrEditWtTask() {
  state.createWtTaskVisible = false;
}
function handleCreateOrEditWtTask() {
  const params = {parentId: state.selectParentTaskId};
  Object.assign(params,state.childWtTaskVO)
  $api.common.send
      .post("wtTask003", params)
      .then(() => {
        $messageBox.success("子任务创建成功", "提示");
        getChildList();
        cancelCreateOrEditWtTask();
      })
      .catch(() => {});
}

function getLogList() {
  $api.common.send
      .post('wtTaskQuery004', {wtTaskAllocationId: state.wtTaskVO.wtTaskAllocationId})
      .then((res) => {
        state.commitLogList = res.result.filter(item => item.operation === 3);
        state.executeLogList = res.result.filter(item => item.operation !== 3);
      })
      .catch(() => {});
}

function resetLogList() {
  state.commitLogList = [];
  state.executeLogList = [];
}

function resetData() {
  state.wtTaskVO = {
    taskName: undefined,
    taskDesc: undefined,
    taskType: undefined,
    taskStartTime: undefined,
    taskEndTime: undefined,
    taskStatus: undefined,
    taskPriority: undefined,
    createFullName: undefined,
    orgName: undefined,
    isAssign: undefined,
    taskLabel: undefined,
    predictWorkHours: undefined,
    completedTime: undefined,
    remarks: undefined,
    taskRealProgress: undefined
  };
  state.selectParentTaskId = undefined;
  resetLogList();
}

onMounted(() => {
  nextTick(() => {
    initDict();
  });
});
</script>

<style scoped  lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>